<template>
  <el-header>
    <div class="l-content">
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item
            v-for="item in tagsValue"
            :key="item.path.name"
            :to="item.path"
        >
          {{ item.authName }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="r-content">
      <div class="center">
        <span class="current-time">{{ currentTime }}</span>
      </div>
      <el-dropdown>
        <span class="el-dropdown-link">
          <img v-if="!ImgUrl" src="@/img/user.png" class="user">
          <img v-else :src="ImgUrl" class="user">
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-if="role === 'user'" @click="gotoSelfInformation">
              个人中心
            </el-dropdown-item>
            <el-dropdown-item v-if="role === 'admin'" @click="gotoUserInformation">
              管理中心
            </el-dropdown-item>
            <el-dropdown-item @click="logOut">退出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </el-header>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useCounterStore } from '../stores/counters.js';
import TokenStorage from '../utils/token';
import { ElMessage } from 'element-plus';
import userApi from '../apis/UserApi.js'; // 导入 UserApi

const store = useCounterStore();
const router = useRouter();

// 用户信息
const ImgUrl = ref('');
const role = ref('');

// 获取用户角色和头像
const getRoleAndAvatar = async () => {
  try {
    const userInfo = TokenStorage.get();
    role.value = userInfo?.role || '';

    // 只有普通用户才调用接口获取头像
    if (role.value === 'user') {
      const avatarRes = await userApi.ViewSelfInformationPhoto();
      if (avatarRes && avatarRes.code === 200) {
        ImgUrl.value = avatarRes.data; // 假设返回的是头像 URL
      } else {
        ImgUrl.value = ''; // 如果没有头像，使用默认图片
      }
    } else {
      ImgUrl.value = ''; // 管理员不调用接口，直接使用默认图片
    }
  } catch (error) {
    console.error('获取头像失败:', error);
    ImgUrl.value = ''; // 使用默认图片
  }
};

// 路由跳转处理
const gotoSelfInformation = () => router.push({ name: 'user-profile' });
const gotoUserInformation = () => router.push({ name: 'admin-users' });

// 退出登录
const logOut = () => {
  store.$reset(); // 使用 Pinia 的重置功能
  TokenStorage.remove();
  router.push({ name: 'login' });
  ElMessage.success('退出成功');
};

// 面包屑导航处理
const tagsValue = computed(() => {
  return store.menuList.map(item => ({
    ...item,
    path: typeof item.path === 'string'
        ? { name: item.path }
        : item.path
  }));
});

// 时间显示
const currentTime = ref('');
const updateCurrentTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-');
};

onMounted(() => {
  getRoleAndAvatar(); // 获取角色和头像
  updateCurrentTime();
  setInterval(updateCurrentTime, 1000);
});
</script>

<style scoped>
header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 55px;
}
.l-content {
  color: #999999;
}
.user {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.el-breadcrumb ::v-deep .el-breadcrumb__inner {
  color: #999 !important;
  font-weight: normal;
}
.breadcrumb-link:hover {
  cursor: pointer;
}
.breadcrumb-link {
  color: #999999;
  font-weight: lighter;
  font-size: 13px;
}
.r-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}
.current-time {
  margin-top: 5px;
  margin-right: 20px;
  color: #999999;
  font-weight: bold;
}
.breadcrumb {
  cursor: pointer;
}
</style>
